<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * Main controller
 */
class Controller_Schema extends Controller_Template {
	protected $_template = 'other/master';

	/**
	 * List of schemas
	 */
	public function indexAction() {
		$this->template->content = View::factory('schema/index')
			->set('schema_list', Schema::getList())
			->render();
	}

	/**
	 * Insert schema
	 */
	public function insertAction($error = -1) {
		if (Input::isPostBack()) {
			$data = array();
			Query::data($data, 'file', Input::post('schema_file'), Query::DATA_STRING);
			Query::data($data, 'status_id', Input::post('schema_status_id'), Query::DATA_INTEGER);

			$new_schema_id = Schema::insert($data);
			if ($new_schema_id) {
				Tools::redirect(BASE_URL . 'schema/update/' . $new_schema_id . '/-2');
			} else {
				Tools::redirect(CURRENT_URL . '1');
			}
		} else {
			$this->template->content = View::factory('schema/insert')
				->set('error', $error)
				->render();
		}
	}

	/**
	 * Update group
	 */
	public function updateAction($id = 0, $error = -1) {
		if (Input::isPostBack()) {
			$data = array();
			Query::data($data, 'file', Input::post('schema_file'), Query::DATA_STRING);
			Query::data($data, 'status_id', Input::post('schema_status_id'), Query::DATA_INTEGER);

			if (Schema::update($id, $data)) {
				Tools::redirect(CURRENT_URL . $id . '/0');
			} else {
				Tools::redirect(CURRENT_URL . $id . '/1');
			}
		} else {
			$info = Schema::getInfo($id);
			$this->template->content = View::factory('schema/update')
				->set('error', $error)
				->set('info', $info)
				->set('title', Schema::getFileTitle($info['file']))
				->render();
		}
	}
	
	/**
	 * Delete group
	 */
	public function deleteAction($id = 0, $error = -1) {
		if (Input::isPostBack()) {
			$data = array();
			Query::data($data, 'status_id', 3, Query::DATA_INTEGER);

			if (Schema::delete($id, $data)) {
				Tools::redirect(CURRENT_URL . $id . '/0');
			} else {
				Tools::redirect(CURRENT_URL . $id . '/1');
			}
		} else {
			$info = Schema::getInfo($id);
			$this->template->content = View::factory('schema/delete')
				->set('error', $error)
				->set('info', $info)
				->set('title', Schema::getFileTitle($info['file']))
				->render();
		}
	}
	
	/**
	 * Change form language
	 */
	public function languageAction($lang_code) {
		$lang_code = trim(strtolower($lang_code));
		if (in_array($lang_code, Config::get('schema_list', 'i18n'))) {
			Session::set('i18n_schema_current', $lang_code);
		}

		Tools::redirect(Input::get('url'));
	}
}